package com.echo.im.client.router.support;


import com.echo.im.client.handler.PushMessageHandler;
import com.echo.im.client.model.IMPlatformMessage;
import com.echo.im.client.router.MessageRouter;
import com.echo.im.client.status.UserStatusService;
import com.echo.im.client.model.IMUserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: echo
 * @time: 2024-08-25
 */
public class PlatformMessageRouter implements MessageRouter<IMPlatformMessage> {


    private final UserStatusService userStatusService;
    private final PushMessageHandler pushMessageHandler;

    public PlatformMessageRouter(UserStatusService userStatusService, PushMessageHandler pushMessageHandler) {
        this.userStatusService = userStatusService;
        this.pushMessageHandler = pushMessageHandler;
    }

    @Override
    public void routeMessage(IMPlatformMessage message) {
        // 根据每个接受者所连的IM-engin-server，进行分组
        Set<Long> offlineUserIdList = new HashSet<>();
        Map<Integer, List<IMUserInfo>> serverIdUserInfoMap = userStatusService.getServerIdUserInfoListMapWithOffline(message.getRecvIds(),offlineUserIdList);

        // 逐个server发送
        serverIdUserInfoMap.forEach(
                (serverId, userInfoList) -> {

                    // 推送至队列
                    pushMessageHandler.pushPlatformMessage( message,userInfoList,serverId.toString());
                }
        );
    }
}
